/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.inmp.task;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.StatefulJob;

import com.sinodata.bsm.common.vo.Event;
import com.sinodata.bsm.common.vo.Res;
import com.sinodata.bsm.inmp.cache.CacheFactory;
import com.sinodata.bsm.inmp.cache.ResCache;
import com.sinodata.bsm.inmp.message.Messenger;
import com.sinodata.bsm.inmp.opconf.OpDbServiceUtil;
import com.sinodata.bsm.inmp.opconf.OpSqlGenerator;
import com.sinodata.bsm.inmp.util.DBConnectionUtil;
import com.sinodata.bsm.inmp.util.FilePersistUtil;
import com.sinodata.bsm.inmp.util.InmpEvent;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author wangyazhou
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2013-6-13 上午10:09:03          wangyazhou        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
@SuppressWarnings("deprecation")
public class OpEventJob implements StatefulJob {

    private static final Logger logger = Logger.getLogger("opevent");

    private static String EVENT_TIME_FILE = "op_event";

    private ResCache resCache = (ResCache) CacheFactory.getCache(ResCache.class);

    private static final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        String lastTime = "";
        String now = "";
        try {
            now = sdf1.parse(OpDbServiceUtil.getInstance().getSingleDbValue("select now()")).getTime() + "";
        } catch (Exception e) {
            logger.error("[ERROR]\tFailed when get postgre current time ", e);
            return;
        }

        try {
            lastTime = (String) FilePersistUtil.getPersistentData(EVENT_TIME_FILE);
        } catch (Exception e) {
            lastTime = "";
        }

        if (lastTime == null || lastTime.length() < 1) {
            try {
                FilePersistUtil.savePersistentData(EVENT_TIME_FILE, now);
                //                FilePersistUtil.savePersistentData(EVENT_TIME_FILE, "1371711307000");
                System.out.println("first");
            } catch (Exception e2) {
                logger.error(e2);
            }
            return;
        }

        //获取到事件并与资源匹配
        String sql = OpSqlGenerator.buildEventSql(lastTime, now);
        List<InmpEvent> eventList = getLastEvents(sql);

        //把事件发送到事件队列
        send(eventList);

        try {
            FilePersistUtil.savePersistentData(EVENT_TIME_FILE, now);
        } catch (Exception e2) {
            logger.error(e2);
        }
    }

    /**
     * 发送事件
     * @param eventList
     */
    private void send(List<InmpEvent> eList) {
        if (eList == null) {
            return;
        }

        logger.info("[TIP]\t Event Size = " + eList.size());
        for (InmpEvent iEvent : eList) {
            try {
                System.out.println(iEvent.toString());
                Res res = resCache.getResIdByIId(iEvent.getSource());
                if (res == null) {
                    continue;
                }
                Event event = new Event();
                event.setResId(res.getId());
                event.setOccurTime(iEvent.getCreateTime());
                event.setEventTypeId(311100000000001L);
                event.setLastOccurTime(iEvent.getModTime());
                event.setMsg(iEvent.getMessage());
                event.setObjectId(iEvent.getEntity());

                if ("5".equals(iEvent.getSeverity())) {//产生一个恢复事件
                    event.setLevel(1);
                    event.setStatus(2);
                    event.setCatalog(2);
                } else { //产生一个新事件
                    event.setLevel(Integer.parseInt(iEvent.getSeverity()) + 1);
                    event.setStatus(0);
                    event.setCatalog(1);
                }

                Messenger.getInstance().sendEvent(event);
            } catch (Exception e) {
                logger.error(e);
            }

        }
    }

    /**
     * 获得最新的事件数据
     * @param sql
     * @return
     */
    private List<InmpEvent> getLastEvents(String sql) {
        logger.info(sql);

        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;
        ResultSetMetaData rsMetaData = null;
        List<InmpEvent> values = new ArrayList<InmpEvent>();
        try {
            conn = DBConnectionUtil.getInstance().getManagerConnection();
            statement = conn.createStatement();
            rs = statement.executeQuery(sql);
            if (rs == null) {
                return null;
            }
            rsMetaData = rs.getMetaData();
            //int numberOfColumns = rsMetaData.getColumnCount();
            while (rs.next()) {
                try {
                    InmpEvent event = new InmpEvent();
                    event.setCreateTime(sdf1.parse(sdf1.format(Long.parseLong(rs.getString(1)))));
                    event.setModTime(sdf1.parse(sdf1.format(Long.parseLong(rs.getString(2)))));
                    event.setPreSeverity(rs.getString(3));
                    event.setSeverity(rs.getString(4));
                    event.setMessage(rs.getString(5));
                    event.setSource(rs.getString(6));
                    event.setEntity(rs.getString(7));
                    event.setEventType(rs.getString(8));
                    event.setAlarmcode(rs.getString(9));
                    event.setId(rs.getString(10));
                    event.toString();
                    values.add(event);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            logger.error(e);
            return null;
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException ex) {

                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {

                }
            }
            DBConnectionUtil.getInstance().returnConn(conn);
        }
        return values;
    }
}
